/**
 * 话术类型定义
 */
import { getLogger } from '@gnlab/utils'
import { type Word, formatIrregularWord } from '@/services/common/definition'

export * from '@/services/common/definition/word'

const logger = getLogger('services/resources/words-library')

/**
 * 一套话术
 */
export interface Words {
  id: number
  isGlobal: boolean // 是否是全局话术
  groupId: number | null // 话术所属分组，为 null 代表没有分组
  items: Word[]
  sort: number
}

export interface RespWords {
  Id: number
  Type: 0 | 1 // 0 代表是全员话术
  GroupId: number
  Content: string
  Sort: number // 此话术的排序
}

export function formatRespWords(raw: RespWords): Words {
  let items: Word[]
  try {
    items = (JSON.parse(raw.Content) as Word[]).map(formatIrregularWord)
  } catch (e) {
    items = []
    logger.warn('解析话术内容失败', raw)
  }
  return {
    id: raw.Id,
    groupId: raw.GroupId === 0 ? null : raw.GroupId,
    isGlobal: raw.Type === 0,
    items,
    sort: raw.Sort,
  }
}

/**
 * 话术分组
 */
export interface WordsGroup {
  id: number
  name: string
  isGlobal: boolean // 是否是全局分组
}

export interface RespWordsGroup {
  Id: number
  Name: string
  Type: 0 | 1 // 0 代表是全员话术
}

export function formatRespWordsGroup(raw: RespWordsGroup): WordsGroup {
  return {
    id: raw.Id,
    name: raw.Name,
    isGlobal: raw.Type === 0,
  }
}
